{% extends "base.html" %}

{% block title %}系统监控{% endblock %}

{% block extra_css %}
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
<style>
    body {
        padding-top: 60px;
    }
    .metric-card {
        background: white;
        border-radius: 10px;
        box-shadow: 0 2px 4px rgba(0,0,0,0.1);
        margin-bottom: 20px;
        padding: 20px;
    }
    .metric-title {
        color: #495057;
        font-size: 1.1rem;
        font-weight: 600;
        margin-bottom: 15px;
    }
    .metric-value {
        font-size: 2rem;
        font-weight: bold;
        color: #0d6efd;
    }
    .status-healthy {
        color: #198754;
    }
    .status-warning {
        color: #ffc107;
    }
    .status-critical {
        color: #dc3545;
    }
    .chart-container {
        position: relative;
        height: 300px;
        margin-bottom: 20px;
    }
</style>
{% endblock %}

{% block content %}
<div class="container">
    <h2 class="mb-4">
        <i class="fas fa-tachometer-alt me-2"></i>
        系统监控面板
    </h2>
    
    <!-- 系统状态 -->
    <div class="row mb-4">
        <div class="col-md-3">
            <div class="metric-card">
                <div class="metric-title">
                    <i class="fas fa-heartbeat me-2"></i>系统状态
                </div>
                <div class="metric-value" id="system-status">
                    <i class="fas fa-circle-notch fa-spin"></i>
                </div>
            </div>
        </div>
        <div class="col-md-3">
            <div class="metric-card">
                <div class="metric-title">
                    <i class="fas fa-microchip me-2"></i>CPU 使用率
                </div>
                <div class="metric-value" id="cpu-usage">
                    <i class="fas fa-circle-notch fa-spin"></i>
                </div>
            </div>
        </div>
        <div class="col-md-3">
            <div class="metric-card">
                <div class="metric-title">
                    <i class="fas fa-memory me-2"></i>内存使用率
                </div>
                <div class="metric-value" id="memory-usage">
                    <i class="fas fa-circle-notch fa-spin"></i>
                </div>
            </div>
        </div>
        <div class="col-md-3">
            <div class="metric-card">
                <div class="metric-title">
                    <i class="fas fa-hdd me-2"></i>磁盘使用率
                </div>
                <div class="metric-value" id="disk-usage">
                    <i class="fas fa-circle-notch fa-spin"></i>
                </div>
            </div>
        </div>
    </div>

    <!-- 请求统计 -->
    <div class="row mb-4">
        <div class="col-md-6">
            <div class="metric-card">
                <div class="metric-title">
                    <i class="fas fa-chart-line me-2"></i>响应时间趋势
                </div>
                <div class="chart-container">
                    <canvas id="response-time-chart"></canvas>
                </div>
            </div>
        </div>
        <div class="col-md-6">
            <div class="metric-card">
                <div class="metric-title">
                    <i class="fas fa-database me-2"></i>数据库连接
                </div>
                <div class="chart-container">
                    <canvas id="db-connections-chart"></canvas>
                </div>
            </div>
        </div>
    </div>

    <!-- 错误率和缓存命中率 -->
    <div class="row">
        <div class="col-md-6">
            <div class="metric-card">
                <div class="metric-title">
                    <i class="fas fa-exclamation-triangle me-2"></i>错误率
                </div>
                <div class="metric-value" id="error-rate">
                    <i class="fas fa-circle-notch fa-spin"></i>
                </div>
            </div>
        </div>
        <div class="col-md-6">
            <div class="metric-card">
                <div class="metric-title">
                    <i class="fas fa-bolt me-2"></i>缓存命中率
                </div>
                <div class="metric-value" id="cache-hit-rate">
                    <i class="fas fa-circle-notch fa-spin"></i>
                </div>
            </div>
        </div>
    </div>
</div>
{% endblock %}

{% block extra_js %}
<script>
    // 更新系统状态的函数
    function updateSystemStatus() {
        fetch('/api/monitoring/health')
            .then(response => response.json())
            .then(data => {
                const statusElement = document.getElementById('system-status');
                const status = data.status;
                const statusClass = {
                    'healthy': 'status-healthy',
                    'warning': 'status-warning',
                    'critical': 'status-critical'
                }[status] || '';
                
                statusElement.innerHTML = `
                    <i class="fas fa-circle ${statusClass}"></i>
                    <span class="${statusClass}">${status.toUpperCase()}</span>
                `;

                // 更新指标
                document.getElementById('cpu-usage').textContent = `${data.metrics.cpu}%`;
                document.getElementById('memory-usage').textContent = `${data.metrics.memory}%`;
                document.getElementById('disk-usage').textContent = `${data.metrics.disk}%`;
            });
    }

    // 更新性能指标的函数
    function updatePerformanceMetrics() {
        fetch('/api/monitoring/performance')
            .then(response => response.json())
            .then(data => {
                // 更新错误率和缓存命中率
                document.getElementById('error-rate').textContent = 
                    `${(data.system.error_rate * 100).toFixed(2)}%`;
                document.getElementById('cache-hit-rate').textContent = 
                    `${(data.system.cache_hit_rate * 100).toFixed(2)}%`;

                // 更新图表
                updateResponseTimeChart(data.request_times.recent);
                updateDbConnectionsChart(data.database);
            });
    }

    // 响应时间图表
    let responseTimeChart;
    function updateResponseTimeChart(data) {
        const ctx = document.getElementById('response-time-chart').getContext('2d');
        
        if (!responseTimeChart) {
            responseTimeChart = new Chart(ctx, {
                type: 'line',
                data: {
                    labels: Array.from({length: data.length}, (_, i) => `请求 ${i + 1}`),
                    datasets: [{
                        label: '响应时间 (ms)',
                        data: data,
                        borderColor: '#0d6efd',
                        tension: 0.1
                    }]
                },
                options: {
                    responsive: true,
                    maintainAspectRatio: false
                }
            });
        } else {
            responseTimeChart.data.datasets[0].data = data;
            responseTimeChart.update();
        }
    }

    // 数据库连接图表
    let dbConnectionsChart;
    function updateDbConnectionsChart(data) {
        const ctx = document.getElementById('db-connections-chart').getContext('2d');
        
        if (!dbConnectionsChart) {
            dbConnectionsChart = new Chart(ctx, {
                type: 'bar',
                data: {
                    labels: ['活跃连接', '总查询', '慢查询'],
                    datasets: [{
                        label: '数据库统计',
                        data: [
                            data.active_connections,
                            data.total_queries,
                            data.slow_queries
                        ],
                        backgroundColor: [
                            '#0d6efd',
                            '#198754',
                            '#dc3545'
                        ]
                    }]
                },
                options: {
                    responsive: true,
                    maintainAspectRatio: false
                }
            });
        } else {
            dbConnectionsChart.data.datasets[0].data = [
                data.active_connections,
                data.total_queries,
                data.slow_queries
            ];
            dbConnectionsChart.update();
        }
    }

    // 定期更新数据
    setInterval(updateSystemStatus, 5000);  // 每5秒更新一次系统状态
    setInterval(updatePerformanceMetrics, 10000);  // 每10秒更新一次性能指标

    // 初始加载
    updateSystemStatus();
    updatePerformanceMetrics();
</script>
{% endblock %} 